import 'dart:ui';

import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/pages/home_page.dart';
import 'package:changxindianzishangwu/pages/login/login_init_page.dart';
import 'package:changxindianzishangwu/provider/conversion.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/provider/friend.dart';
import 'package:changxindianzishangwu/provider/friendApplication.dart';
import 'package:changxindianzishangwu/provider/groupApplication.dart';
import 'package:changxindianzishangwu/provider/keybooadshow.dart';
import 'package:changxindianzishangwu/provider/nickname.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/routers/routers.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/config.dart';
import 'package:changxindianzishangwu/widget/loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimConversationListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimFriendshipListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimGroupListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSDKListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSignalingListener.dart';
import 'package:tencent_im_sdk_plugin/enum/log_level.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_application_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message_receipt.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';
import 'package:flutter_bugly/flutter_bugly.dart';

import 'cache/local_cache.dart';
import 'dao/user_info_dao.dart';
import 'db/ec_cache.dart';
import 'pages/login/login_update_info_page.dart';

main() {
  SystemUiOverlayStyle style = SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
  );
  SystemChrome.setSystemUIOverlayStyle(style);

  WidgetsFlutterBinding.ensureInitialized();

  FlutterBugly.postCatchedException(() => runApp(MultiProvider(providers: [
        ChangeNotifierProvider(create: (_) => ConversionModel()),
        ChangeNotifierProvider(create: (_) => UserModel()),
        ChangeNotifierProvider(create: (_) => CurrentMessageListModel()),
        ChangeNotifierProvider(create: (_) => FriendListModel()),
        ChangeNotifierProvider(create: (_) => NickName()),
        ChangeNotifierProvider(create: (_) => FriendApplicationModel()),
        ChangeNotifierProvider(create: (_) => GroupApplicationModel()),
        ChangeNotifierProvider(create: (_) => KeyBoradModel()),
      ], child: MyApp())));
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>
    with WidgetsBindingObserver, ChangeNotifier {
  AppLifecycleState _notification;
  String pageName = "example.main";
  AppLifecycleState currentState = AppLifecycleState.resumed;
  Widget init;
  bool isinit = false;

  final XgFlutterPlugin tpush = new XgFlutterPlugin();

  @override
  void dispose() {
    EasyLoading.dismiss();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _main();
  }

  Future initApp() async {
    return Future.wait([EcCache.preInit(), getUser(), loginIm()]);
  }

  _main() {
    return FutureBuilder(
        future: initApp(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            init = Loading();
          } else {
            if (ObjectUtil.isEmptyString(getAppLoginToken())) {
              init = LoginInitPage();
            } else {
              EasyLoading.show(status: "正在登录...");
              if (getUserInfo().isFirstIn == 0) {
                init = LoginUpdateInfoPage();
              } else {
                init = HomePage();
              }
            }
          }
          EasyLoading.dismiss();

          return ScreenUtilInit(
            designSize: Size(375, 812),
            builder: () => GetMaterialApp(
              title: "自语",
              theme: ThemeData(primarySwatch: white, fontFamily: 'Poppins'),
              debugShowCheckedModeBanner: false,
              getPages: Routers.page,
              home: init,
              builder: EasyLoading.init(),
              // onGenerateRoute: (RouteSettings settings) {
              //   return Routers.routers(settings);
              // },
            ),
          );
        });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive:
        //  应用程序处于闲置状态并且没有收到用户的输入事件。
        //注意这个状态，在切换到后台时候会触发，所以流程应该是先冻结窗口，然后停止UI
        print('YM----->AppLifecycleState.inactive');
        break;
      case AppLifecycleState.paused:
//      应用程序处于不可见状态

        if (GetPlatform.isAndroid) {
          TencentImSDKPlugin.v2TIMManager
              .getOfflinePushManager()
              .doBackground(unreadCount: 0);
        }
        print('YM----->AppLifecycleState.paused');
        EcCache.getInstance().setBool("leaveState", true);
        break;
      case AppLifecycleState.resumed:
        //    进入应用时候不会触发该状态
        if (GetPlatform.isAndroid) {
          TencentImSDKPlugin.v2TIMManager
              .getOfflinePushManager()
              .doForeground();
        }

        //  应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume。
        print('YM----->AppLifecycleState.resumed');
        EcCache.getInstance().setBool("leaveState", false);
        break;
      case AppLifecycleState.detached:
        //当前页面即将退出
        print('YM----->AppLifecycleState.detached');
        break;
    }
  }

  @override
  void initState() {
    initPlatformState();
    loadAsync();
    initWx();

    super.initState();
    initMap();
    initBugly();
    // loginIm();
    WidgetsBinding.instance.addObserver(this); //添加观察者
    inits();
  }

  initWx() async {
    var initWxBool = await registerWxApi(
      appId: AppString.WX_APP_ID, //传入注册的应用id
      doOnAndroid: true, //在android上运行
      doOnIOS: true, // 在ios上运行
      universalLink: AppString.WX_LINKS,
    );

    // var result = await isWeChatInstalled;
    // print("WX is installed $result");
    print("WX is installed $initWxBool");
  }

  Future getUser() async {
    if (!ObjectUtil.isEmptyString(getAppLoginToken())) {
      return await UserInfoDao.getUserInfo();
    }
  }

  void loadAsync() {
    EcCache.preInit();
  }

  inits() async {
    await initSDK();
    setState(() {
      isinit = true;
    });
    // await islogin();
    // await toHomePage();
    // await setOfflinepush();
  }

  Future<bool> loginIm() async {
    if (ObjectUtil.isEmptyString(getAppLoginToken())) {
      return false;
    }
    await TencentImSDKPlugin.v2TIMManager
        .login(
      userID: getUserId(),
      userSig: getUserSig(),
    )
        .then((res) async {
      if (res.code == 0) {
        EasyLoading.dismiss();
        // showToast("自动登录 √ 登录成功");
        // print("_______" + EcCache.getInstance().get('userId'));
        tpush.setAccount(
            EcCache.getInstance().get('userId'), AccountType.UNKNOWN);
        return true;
      } else {
        return false;
      }
    });
  }

  void onSelfInfoUpdated() async {
    //自己信息更新，从新获取自己的信息；

    V2TimValueCallback<String> usercallback =
        await TencentImSDKPlugin.v2TIMManager.getLoginUser();
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [usercallback.data]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  void onKickedOffline() async {
// 被踢下线
    // 清除本地缓存，回到登录页TODO
    try {
      Provider.of<ConversionModel>(context, listen: false).clear();
      Provider.of<UserModel>(context, listen: false).clear();
      Provider.of<CurrentMessageListModel>(context, listen: false).clear();
      Provider.of<FriendListModel>(context, listen: false).clear();
      Provider.of<FriendApplicationModel>(context, listen: false).clear();
      Provider.of<GroupApplicationModel>(context, listen: false).clear();
      // 去掉存的一些数据
      Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
      SharedPreferences prefs = await _prefs;
      prefs.remove('token');
      prefs.remove('sessionId');
      prefs.remove('phone');
      prefs.remove('code');
      Get.offAll(LoginInitPage());
    } catch (err) {
      print("someError");
      print(err);
    }
    print("被踢下线了");
  }

  void onReceiveJoinApplicationonMemberEnter() async {
    V2TimValueCallback<V2TimGroupApplicationResult> res =
        await TencentImSDKPlugin.v2TIMManager
            .getGroupManager()
            .getGroupApplicationList();
    if (res.code == 0) {
      if (res.code == 0) {
        if (res.data.groupApplicationList.length > 0) {
          Provider.of<GroupApplicationModel>(context, listen: false)
              .setGroupApplicationResult(res.data.groupApplicationList);
        }
      }
    } else {
      print("获取加群申请失败${res.desc}");
    }
  }

  void onRecvNewMessage(V2TimMessage message) {
    try {
      List<V2TimMessage> messageList = List.empty(growable: true);

      messageList.add(message);

      print("c2c_${message.sender}");
      String key;
      if (message.groupID == null) {
        key = "c2c_${message.sender}";
      } else {
        key = "group_${message.groupID}";
      }
      print("conterkey_$key");
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(key, messageList);
    } catch (err) {
      print(err);
    }
  }

  void onRecvC2CReadReceipt(List<V2TimMessageReceipt> list) {
    print('收到了新消息 已读回执');
    list.forEach((element) {
      print("已读回执${element.userID} ${element.timestamp}");
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .updateC2CMessageByUserId(element.userID);
    });
  }

  void onSendMessageProgress(V2TimMessage message, int progress) {
// 消息进度
    String key;
    if (message.groupID == null) {
      key = "c2c_${message.userID}";
    } else {
      key = "group_${message.groupID}";
    }
    try {
      Provider.of<CurrentMessageListModel>(
        context,
        listen: false,
      ).addOneMessageIfNotExits(
        key,
        message,
      );
    } catch (err) {
      print("error $err");
    }
    print(
        "消息发送进度 $progress ${message.timestamp} ${message.msgID} ${message.timestamp} ${message.status}");
  }

  void
      onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted() async {
    V2TimValueCallback<List<V2TimFriendInfo>> friendRes =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .getFriendList();
    if (friendRes.code == 0) {
      List<V2TimFriendInfo> newList = friendRes.data;
      if (newList != null && newList.length > 0) {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(newList);
      } else {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(List.empty(growable: true));
      }
    }
  }

  void onFriendApplicationListAdded(List<V2TimFriendApplication> list) {
    // 收到加好友申请,添加双向好友时双方都会周到这个回调，这时要过滤掉type=2的不显示
    print("收到加好友申请");
    List<V2TimFriendApplication> newlist = List.empty(growable: true);
    list.forEach((element) {
      if (element.type != 2) {
        newlist.add(element);
      }
    });
    if (newlist.isNotEmpty) {
      Provider.of<FriendApplicationModel>(context, listen: false)
          .setFriendApplicationResult(newlist);
    }
  }

  Map<String, V2TimConversation> conversationlistToMap(
      List<V2TimConversation> list) {
    Map<int, V2TimConversation> convsersationMap = list.asMap();
    Map<String, V2TimConversation> newConversation = new Map();
    convsersationMap.forEach((key, value) {
      newConversation[value.conversationID] = value;
    });
    return newConversation;
  }

  initSDK() async {
    V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
    await timManager.initSDK(
      sdkAppID: HttpUrls.imSdkAppId(),
      loglevel: LogLevel.V2TIM_LOG_DEBUG,
      listener: new V2TimSDKListener(
        onConnectFailed: (code, error) {},
        onConnectSuccess: () {},
        onConnecting: () {},
        onKickedOffline: () {
          onKickedOffline();
        },
        onSelfInfoUpdated: (info) {
          onSelfInfoUpdated();
        },
        onUserSigExpired: () {},
      ),
    );

    print("initSDK");

    //群组监听
    timManager.setGroupListener(
      listener: new V2TimGroupListener(
        onApplicationProcessed: (groupID, opUser, isAgreeJoin, opReason) {},
        onGrantAdministrator: (groupID, opUser, memberList) {},
        onGroupAttributeChanged: (groupID, groupAttributeMap) {},
        onGroupCreated: (groupID) {},
        onGroupDismissed: (groupID, opUser) {},
        onGroupInfoChanged: (groupID, changeInfos) {},
        onGroupRecycled: (groupID, opUser) {},
        onMemberEnter: (groupID, memberList) {
          onReceiveJoinApplicationonMemberEnter();
        },
        onMemberInfoChanged: (groupID, v2TIMGroupMemberChangeInfoList) {},
        onMemberInvited: (groupID, opUser, memberList) {},
        onMemberKicked: (groupID, opUser, memberList) {},
        onMemberLeave: (groupID, member) {},
        onQuitFromGroup: (groupID) {},
        onReceiveJoinApplication: (groupID, member, opReason) {
          onReceiveJoinApplicationonMemberEnter();
        },
        onReceiveRESTCustomData: (groupID, customData) {},
        onRevokeAdministrator: (groupID, opUser, memberList) {},
      ),
    );
    //高级消息监听
    timManager.getMessageManager().addAdvancedMsgListener(
          listener: new V2TimAdvancedMsgListener(
            onRecvC2CReadReceipt: (receiptList) {
              onRecvC2CReadReceipt(receiptList);
            },
            onRecvMessageRevoked: (msgID) {},
            onRecvNewMessage: (msg) {
              //toast("onRecvNewMessage！");
              onRecvNewMessage(msg);
            },
            onSendMessageProgress: (message, progress) {
              //toast("onSendMessageProgress！");
              onSendMessageProgress(message, progress);
            },
          ),
        );

    timManager.getFriendshipManager().setFriendListener(
          listener: new V2TimFriendshipListener(
            onBlackListAdd: (infoList) {},
            onBlackListDeleted: (userList) {
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
            },
            onFriendApplicationListAdded: (applicationList) {
              onFriendApplicationListAdded(applicationList);
            },
            onFriendApplicationListDeleted: (userIDList) {},
            onFriendApplicationListRead: () {},
            onFriendInfoChanged: (infoList) {
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
            },
            onFriendListAdded: (users) {
              //onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
            },
            onFriendListDeleted: (userList) {
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
            },
          ),
        );
    //会话监听
    timManager.getConversationManager().setConversationListener(
          listener: new V2TimConversationListener(
            onConversationChanged: (conversationList) {
              try {
                Provider.of<ConversionModel>(context, listen: false)
                    .setConversionList(conversationList);
                //如果当前会话在使用中，也更新一下

              } catch (e) {}
            },
            onNewConversation: (conversationList) {
              try {
                //showToast("来新会话了！");
                Provider.of<ConversionModel>(context, listen: false)
                    .setConversionList(conversationList);
                //如果当前会话在使用中，也更新一下

              } catch (e) {}
            },
            onSyncServerFailed: () {},
            onSyncServerFinish: () {},
            onSyncServerStart: () {},
          ),
        );
    timManager.getSignalingManager().addSignalingListener(
          listener: new V2TimSignalingListener(
            onInvitationCancelled: (inviteID, inviter, data) {},
            onInvitationTimeout: (inviteID, inviteeList) {},
            onInviteeAccepted: (inviteID, invitee, data) {},
            onInviteeRejected: (inviteID, invitee, data) {},
            onReceiveNewInvitation:
                (inviteID, inviter, groupID, inviteeList, data) {},
          ),
        );
    print("初始化完成了");
  }

  ///------------------推送 start-----------------------------------------------

// 收到消息的回调
  Future<dynamic> onPush(Map<String, dynamic> data) {
    return Future.value();
  }

// 点击消息的回调
  Future<dynamic> onResume(Map<String, dynamic> data) {
    // 这里完成用户的逻辑
    return Future.value();
  }

// 静默push的回调
  Future<dynamic> onBackgroundPush(Map<String, dynamic> data) async {
    return Future.value();
  }

// 冷启动点击通知栏的回调
  Future<dynamic> onLaunch(Map<String, dynamic> data) {
    return Future.value();
  }

  /// android

  Future<void> initPlatformState() async {
    if (!mounted) return;

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      String appName = packageInfo.appName;
      String packageName = packageInfo.packageName;
      String version = packageInfo.version;
      // String buildNumber = packageInfo.buildNumber;
      print('PackageInfo appName:$appName');
      print('PackageInfo packageName:$packageName');
      print('PackageInfo version:$version');
    });

    /// 开启DEBUG
    tpush.setEnableDebug(true);

    /// 添加回调事件
    tpush.addEventHandler(
      onRegisteredDeviceToken: (String msg) async {
        print("flutter onRegisteredDeviceToken: $msg");
      },
      onRegisteredDone: (String msg) async {
        print("flutter onRegisteredDone: $msg");
        //_showAlert("注册成功");
      },
      unRegistered: (String msg) async {
        print("flutter unRegistered: $msg");
        //_showAlert(msg);
      },
      onReceiveNotificationResponse: (Map<String, dynamic> msg) async {
        print("flutter onReceiveNotificationResponse $msg");
      },
      onReceiveMessage: (Map<String, dynamic> msg) async {
        print("flutter onReceiveMessage $msg");
      },
      xgPushDidSetBadge: (String msg) async {
        print("flutter xgPushDidSetBadge: $msg");
        // tpush.setBadge(0);
        //
        // /// 在此可设置应用角标
        // tpush.setAppBadge(0);

        //_showAlert(msg);
      },
      xgPushDidBindWithIdentifier: (String msg) async {
        print("flutter xgPushDidBindWithIdentifier: $msg");
        //_showAlert(msg);
      },
      xgPushDidUnbindWithIdentifier: (String msg) async {
        print("flutter xgPushDidUnbindWithIdentifier: $msg");
        // _showAlert(msg);
      },
      xgPushDidUpdatedBindedIdentifier: (String msg) async {
        print("flutter xgPushDidUpdatedBindedIdentifier: $msg");
        //_showAlert(msg);
      },
      xgPushDidClearAllIdentifiers: (String msg) async {
        print("flutter xgPushDidClearAllIdentifiers: $msg");
        // _showAlert(msg);
      },
      xgPushClickAction: (Map<String, dynamic> msg) async {
        print("flutter xgPushClickAction $msg");
        //_showAlert("flutter xgPushClickAction");
      },
    );

    /// 如果您的应用非广州集群则需要在startXG之前调用此函数
    /// 香港：tpns.hk.tencent.com
    /// 新加坡：tpns.sgp.tencent.com
    /// 上海：tpns.sh.tencent.com
    // tpush.configureClusterDomainName("tpns.hk.tencent.com");

    /// 启动TPNS服务
    ///
    ///

    if (GetPlatform.isAndroid) {
      XgFlutterPlugin.xgApi.enableOtherPush();
      String a = await XgFlutterPlugin.otherPushType;
      bool xiaomi = await XgFlutterPlugin.xgApi.isMiuiRom();
      bool huawei = await XgFlutterPlugin.xgApi.isEmuiRom();
      bool oppo = await XgFlutterPlugin.xgApi.isOppoRom();
      bool vivo = await XgFlutterPlugin.xgApi.isVivoRom();
      bool meizu = await XgFlutterPlugin.xgApi.isMeizuRom();
      if (huawei) {
        XgFlutterPlugin.xgApi.startHuaWeiPush();
      } else if (xiaomi) {
        XgFlutterPlugin.xgApi
            .startMiPush(appId: "2882303761519985960", appKey: "5961998538960");
      } else if (oppo) {
        XgFlutterPlugin.xgApi.startOPPOPush(
            appId: "30582993", appKey: "6b3bc43e68b644c9bb4bfd31519b3c6b");
      } else if (vivo) {
        XgFlutterPlugin.xgApi.startViVOPush();
      }
      // showToast(a);
      String v = await XgFlutterPlugin.xgApi.getOtherPushToken();
      print("token!!!!!" + v);
      XgFlutterPlugin.xgApi.regPush();
    } else {
      tpush.startXg("1600021681", "II8FOF0R9N2L");
    }
  }

  ///------------------推送 end-----------------------------------------------
  ///------------------地图 start-----------------------------------------------
  initMap() async {
    // AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  // void requestAccuracyAuthorization() async {
  //   AMapAccuracyAuthorization currentAccuracyAuthorization = await _locationPlugin.getSystemAccuracyAuthorization();
  //   if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
  //     print("精确定位类型");
  //   } else if (currentAccuracyAuthorization == AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
  //     print("模糊定位类型");
  //   } else {
  //     print("未知定位类型");
  //   }
  // }
  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///------------------地图 end-----------------------------------------------
  ///------------------bugly start-----------------------------------------------
  initBugly() {
    FlutterBugly.init(
      androidAppId: "1f4d53e10a",
      iOSAppId: "857fc81e22",
      customUpgrade: true, // 调用Android原生升级方式
    );
    // then((_result) {
    //   setState(() {
    //     _platformVersion = _result.message!;
    //     print(_result.appId);
    //   });
    // });
    // // 当配置 customUpgrade=true 时候，这里可以接收自定义升级
    // FlutterBugly.onCheckUpgrade.listen((_upgradeInfo) {
    //   _showUpdateDialog(_upgradeInfo.newFeature!, _upgradeInfo.apkUrl!,
    //       _upgradeInfo.upgradeType == 2);
    // });
    // FlutterBugly.setUserId("user id");
    // FlutterBugly.putUserData(key: "key", value: "value");
    // int tag = 9527;
    // FlutterBugly.setUserTag(tag);
    //autoCheckUpgrade为true时，可以不用调用
    // if (mounted) _checkUpgrade();
  }

  ///------------------bugly end-----------------------------------------------

}
